#include "externalsort.h"

using namespace std;

int main(int argc, char* argv[]) {

    if(argc < 4)
    {
        std::cerr << "usage: " << argv[0];
        std::cerr << " <input file> <output file> <memory buffer in MB>" << std::endl;
        return -1;
    }
    
    unsigned int bufSiz = atoi(argv[3]);
    if(bufSiz < 1)
    {
        std::cerr << "invalid buffer size: " << argv[3] << std::endl;
    }
    // try to open input file
    int fdInput;
    if((fdInput = open(argv[1], O_RDONLY,  S_IREAD)) < 0) 
    {
        std::cerr << "error opening input file: " << strerror(errno) << std::endl;
        return 1;
    }
    struct stat fileStat;
    if(fstat(fdInput, &fileStat) < 0)
    {
        std::cerr << "error getting filesize of input file: " << strerror(errno) << std::endl;
        return 1;
    }
    
    std::cout << "filesize: " << fileStat.st_size << std::endl;
    
    // try to open output file(s)
    int fdOutput;
    if((fdOutput=open(argv[2], O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR))<0)
    {
        std::cerr << "error opening output file: " << strerror(errno) << std::endl;
        return 1;
    }
    
    unsigned long size = fileStat.st_size / sizeof(uint64_t);
    unsigned long memSize=1024*1024*bufSiz;
    
    // do the sorting
    externalSort(fdInput, size, fdOutput, memSize);
    
    // close the files
    close(fdInput);
    close(fdOutput);
}
